<?php
namespace Admin\Controller\Goods;
use Admin\Controller\Auto\AutoController;
class TypeController extends AutoController {
	public function add(){
		$data = self::Cates();
		$this->list = $data;
		$this->display();
	}

	public static function Cates($mylimit,$ilimit,$keyword){

		$type = M('g_type');
		if(!empty($keyword)){
			$where['a.type_name'] = array('LIKE', '%'.$keyword.'%');
		}
		$count = $type->alias('a')->where($where)->count();
		$limit = ($ilimit-1)*$mylimit;
		$num = $count/$mylimit;
		// alias('a')->field('a.*,b.title as ptitle,concat(a.path,",",a.id) as paths')->join('left join lamp_cate b on a.pid=b.id')
		$data = $type->alias('a')
			->field(array('a.*,b.type_name as pname,concat(a.path,",",a.id) as apath'))
			->join('left join think_g_type b on a.pid=b.id')
			->where($where)
			->order('apath')
			->limit($limit,$mylimit)
			->select();
		$data[count($data)]=ceil($num);
		foreach($data as $k=>&$v){
			$v['type_name']=str_repeat('|---',count(explode(',',$v['apath']))-1).$v['type_name'];
		}
		return $data;
	}
	public function insert(){
		$type = D('g_type');
		$data=$_POST;
		if($_POST['pid']==0){
			$data['path']=0;
		}else{
			$list = $type->find($_POST['pid']);
			$data['path'] = $list['path'].','.$list['id'];
		}
		$data['type_name']=trim($data['type_name']);
		if(empty($data['type_name'])){
			echo '1秒后自动关闭,分类名不能为空';die;
		}

		// var_dump($type->create());die;
		if(!$type->create($data)){
			
			exit($User->getError());
			echo 'no';
			
		}else{
			$type->add();
			echo 'yes';
		}
	}
	public function limit(){
   		$data = self::Cates(I('get.mylimit'),I('get.ilimit'),I('get.keyword'));
   		echo json_encode($data);
	}
   	public function index(){   		
   		$this->list = $data;
   		$this->display();
   	}
   	public function update(){
   		$type = M('g_type');
   		$data = I('post.');
   		$data['type_name'] = ltrim(I('post.type_name'),'|---');
   		$data['type_name']=trim($data['type_name']);
		if(empty($data['type_name'])){
			echo 'no';die;
		}
   		$type->create($data);
   		if($type->save()){
   			echo 'yes';
   		}else{
   			echo 'no';
   		}

   	}
   	public function del(){
   		$type = M('g_type');
   		$data = $type->find(I('post.id'));
   		$path = $data['path'].','.$data['id'];
   		// var_dump($path);
   		$type->where('path like "'.$path.'%"')->delete();
   		if($type->delete(I('post.id'))){
   			echo 'yes';
   		}else{
   			echo 'no';
   		}
   	}
}